﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Drawing.Imaging;
using Accountability4net.Contact;
using MySql.Data.MySqlClient;
using System.IO;
using System.Drawing;

namespace Accountability4net.MySQLDbProvider
{
    public class MySQLDbContact: BaseContact
    {
        MySQLDbProvider provider_;
        protected MySQLDbContact()
            : base()
        {
        }

        public MySQLDbContact(MySQLDbProvider provider)
            : this()
        {
            provider_ = provider;
        }

        public void WirePropertyChanged()
        {
            PropertyChanged += MySQLDbContact_PropertyChanged;
            ((MySQLDbName)Name).PropertyChanged += MySQLDbContact_PropertyChanged;
        }

        public override IName Name
        {
            get
            {
                if (name_ == null)
                {
                    name_ = new MySQLDbName(provider_, this);
                }
                return name_;
            }
            set
            {
                base.Name = value;
            }
        }
        
        public void MySQLDbContact_PropertyChanged(object sender, System.ComponentModel.PropertyChangedEventArgs e)
        {
            string sql = @"UPDATE `contact`
                SET `id` = @id
                , `email` = @email
                , `name.familyName` = @familyName
                , `name.givenName` = @givenName
                , `name.additionalNames` = @additionalNames
                , `name.namePrefix` = @namePrefix
                , `name.nameSuffix` = @nameSuffix
                , `name.formattedName` = @formattedName
                , `photo` = @photo
                WHERE `id` = @id";
            using (var command = new MySqlCommand(sql, provider_.Connection))
            {
                byte[] imageBytes;
                using (var stream = new MemoryStream())
                {
                    if (this.Photo != null)
                    {
                        this.Photo.Save(stream, ImageFormat.Png);
                    }
                    stream.Position = 0;
                    imageBytes = stream.ToArray();
                }
                command.Parameters.AddRange(new MySqlParameter[] 
                {
                    new MySqlParameter("@id", this.ID)
                    , new MySqlParameter("@email", this.Email)
                    , new MySqlParameter("@familyName", this.Name.FamilyName)
                    , new MySqlParameter("@givenName", this.Name.GivenName)
                    , new MySqlParameter("@additionalNames", this.Name.AdditionalNames)
                    , new MySqlParameter("@namePrefix", this.Name.NamePrefix)
                    , new MySqlParameter("@nameSuffix", this.Name.NameSuffix)
                    , new MySqlParameter("@formattedName", this.Name.FormattedName)
                    , new MySqlParameter("@photo", imageBytes)
                });
                int rows = command.ExecuteNonQuery();
            }
        }

        public static MySQLDbContact Create(MySQLDbProvider provider)
        {
            MySQLDbContact contact = new MySQLDbContact(provider);
            contact.ID = Guid.NewGuid();
            string sql = "INSERT INTO `contact` (`id`) VALUES (@id)";
            using (var command = new MySqlCommand(sql, provider.Connection))
            {
                command.Parameters.Add(new MySqlParameter("@id", contact.ID));
                int rows = command.ExecuteNonQuery();
            }
            contact.WirePropertyChanged();
            return contact;
        }

        public static IContact Retrieve(MySQLDbProvider provider, Guid id)
        {
            MySQLDbContact contact = new MySQLDbContact(provider);
            string sql = "SELECT * FROM `contact` WHERE `id` = @id";
            using (var command = new MySqlCommand(sql, provider.Connection))
            {
                MySqlParameter idParameter = new MySqlParameter("@id", id);
                command.Parameters.Add(idParameter);
                using (var reader = command.ExecuteReader())
                {
                    if (reader.Read())
                    {
                        contact.ID = new Guid(reader.GetString("id"));
                        contact.Email = reader.GetString("email");
                        contact.Name.FamilyName = provider.GetString(reader,"name.familyName");
                        contact.Name.GivenName = provider.GetString(reader, "name.givenName");
                        contact.Name.AdditionalNames = provider.GetString(reader, "name.additionalNames");
                        contact.Name.NamePrefix = provider.GetString(reader, "name.namePrefix");
                        contact.Name.NameSuffix = provider.GetString(reader, "name.nameSuffix");
                        contact.Name.FormattedName = provider.GetString(reader, "name.formattedName");
                        byte[] buffer = new byte[1000];
                        using (var stream = new MemoryStream())
                        {
                            long index = 0;
                            long count = 0;
                            do
                            {
                                try
                                {
                                    count = reader.GetBytes(reader.GetOrdinal("photo"), index, buffer, 0, buffer.Length);
                                    index += count;
                                    stream.Write(buffer, 0, (int)count);
                                    stream.Flush();
                                }
                                catch (IndexOutOfRangeException)
                                {
                                    // This just means that we have read all we can
                                    break;
                                }
                            } while (count > 0);
                            stream.Position = 0;
                            contact.Photo = Bitmap.FromStream(stream);
                        }
                    }
                    else
                    {
                        return null;
                    }
                    reader.Close();
                }
            }
            contact.WirePropertyChanged();
            return contact;
        }
    }
}
